/**
 * 
 */
package com.rodirod.vrmonitor;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import net.htmlparser.jericho.Config;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.LoggerProvider;
import net.htmlparser.jericho.Source;
import net.htmlparser.jericho.TextExtractor;



/**
 * @author T0008086
 *
 */
public class UrlReader {

	private String urlPath_ = "";

	/**
	 * 
	 */
	public UrlReader(String urlPath) {
		urlPath_ = urlPath;
		Config.LoggerProvider = LoggerProvider.DISABLED;
	}

	public void fillData(RaceInfo info) throws IOException {
		
		URL url = new URL(urlPath_);
		Source source = new Source(url);

		Element tableElt = source.getFirstElement(HTMLElementName.TABLE);
		if (null!=tableElt) {
			List<Element> listRows = tableElt.getAllElements(HTMLElementName.TR);
			if (null!=listRows) {
				for (int irow=0 ; irow < listRows.size() ; irow++) {
					Element rowElt = listRows.get(irow);
					List<Element> listCells = rowElt.getAllElements(HTMLElementName.TD);
					if (listCells.size()>=2) {
						String field = processCell(listCells.get(0));
						String value = processCell(listCells.get(1));
						if (field.trim().length()>0) info.setField(field,value);
					}
				}
			} else {
				throw new IOException("Error parsing URL data");
			}
		} else {
			throw new IOException("Error parsing URL data");
		}
	}

	/**
	 * 
	 * @param col
	 * @return
	 */
	public String processCell(Element col) {
		return digupStringNode(col);
	}

	/**
	 *
	 * @return the first text node value in the Element tree
	 */
	public String digupStringNode(Element elt) {
		TextExtractor txtExtr = elt.getTextExtractor();
		return txtExtr.toString();
	}

}
